package com.yiwenup.leetcode.site;

import com.yiwenup.leetcode.ListNode;

/**
 * 文件描述
 *
 * @Project struct-algorithm
 * @Package com.yiwenup.leetcode.site
 * @Author yiwenup
 * @Date 2024-12-15 14:54:54
 * @Description https://leetcode.cn/problems/linked-list-cycle-ii/description/
 */
public class No0142 {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                ListNode idx1 = fast;
                ListNode idx2 = head;
                while(idx1 != idx2) {
                    idx1 = idx1.next;
                    idx2 = idx2.next;
                }
                return idx1;
            }
        }

        return null;
    }
}
